<template>
  <div class="cmscomen accountData">
    <div class="infoTable" :style="{ paddingLeft: paddingWidth + 'px'}">
      <div class="topMenu">
        <span>信息流数据管理</span>
        <span style="padding:0 4px;">/</span>
        <span class="two">账号数据</span>
      </div>
      <div class="formInfo">
        <el-date-picker
          v-model="dateValue"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="dateChange">
        </el-date-picker>
        <el-select v-model="platform_items.model_value" :placeholder="platform_items.placeHolder" @change="selectOne" clearable filterable >
          <el-option
            v-for="item in platform_items.options"
            :key="item.platformId"
            :label="item.platformName"
            :value="item.platformId">
          </el-option>
        </el-select>
        <el-select v-model="pro_items.model_value" :placeholder="pro_items.placeHolder" @change="selectTwo" clearable filterable>
          <el-option
              v-for="item in pro_items.options"
              :key="item.productId"
              :label="item.productName"
              :value="item.productId">
          </el-option>
        </el-select>
        <el-select v-model="account_items.model_value" :placeholder="account_items.placeHolder" @change="selectThree" filterable clearable>
          <el-option
              v-for="item in account_items.options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="accountBtn">
        <el-row>
          <el-button type="primary" @click.stop="importData">导出数据</el-button>
          <el-select v-model="importPlatform" placeholder="导入数据所属平台" clearable>
              <el-option
                  v-for="item in platform_items.options"
                  :key="item.platformId"
                  :label="item.platformName"
                  :value="item.platformId">
              </el-option>
          </el-select>
          <el-upload
              class="upload-demo"
              :action="apiUrl.fdpAccImport"
              :data="uploadData"
              :with-credentials="true"
              :on-success="handleSuccess"
              :beforeUpload="beforeAvatarUpload"
              :onError="uploadError"
              :show-file-list="false"
              :file-list="fileList">
              <el-button type="primary">导入数据</el-button>
          </el-upload>
          <a href="http://kydev.oss-cn-beijing.aliyuncs.com/file/importModel.xlsx">
              <el-button type="primary">下载模板</el-button>
          </a>
        </el-row>
      </div>
      <div class="accountWra">
        <div class="AccounTop"></div>
        <div class="AccountableWar gxw-con">
          <el-table
            :data="tableData"
            border
            stripe
            style="width: 100%"
            v-loading="loading"
            element-loading-text="拼命加载中">
              <el-table-column
                  v-for="c in table_column"
                  :key="c.prop"
                  :fixed="c.fixed"
                  :sortable="c.sortable"
                  :prop="c.prop"
                  :label="c.label"
                  :formatter="c.format"
                  width="auto"
                  :min-width="c.minwidth"
                  v-if="c.visible"
                  :show-overflow-tooltip="true">
              </el-table-column>
              <el-table-column
                  label="今日消耗"
                  min-width="150"
                  class-name="exitInput">
                  <template slot-scope="scope">
                      <div class="Inp"><span v-if="scope.row.dataTime=='总计'">{{scope.row.todayConsume}}</span>
                          <el-input v-if="scope.row.dataTime!='总计'" type="number" class="" placeholder="" :value="scope.row.todayConsume"
                                    @change="scope.row.newTodayConsume=changeInput($event)" style="width:80%!important;"></el-input></div>
                  </template>
              </el-table-column>
              <el-table-column
                  v-for="c in table_column_"
                  :key="c.prop"
                  :fixed="c.fixed"
                  :sortable="c.sortable"
                  :prop="c.prop"
                  :label="c.label"
                  :formatter="c.format"
                  width="auto"
                  :min-width="c.minwidth"
                  v-if="c.visible">
              </el-table-column>
              <el-table-column
                  label="操作"
                  min-width="50"
                  class-name="exitBut"
                  align="center">
                  <template slot-scope="scope">
                     <el-tooltip class="item" effect="dark" content="修改" placement="top">
                        <el-button style="padding:3px 3px" type="primary" class="inlineBox icon iconfont icon-tubiao109" circle v-if="scope.row.dataTime!='总计'" @click="updateConsume(scope.row.newTodayConsume,scope.row.id)"></el-button>
                      </el-tooltip>
                  </template>
              </el-table-column>
          </el-table>
        </div>
        <div class="block">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="page.currentPage"
                :page-sizes="page.sizes"
                :page-size="page.limit"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.count">
            </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
export default {
  name:'accountData',
  data(){
    return{
      dateValue: '',
      loading:false,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      uploadData:{platformId:''},
      fileList: [],
      tableData: [],
      table_column: [
          {fixed: false, prop: 'dataTime', label: '日期', sortable: true, visible: true},
          {fixed: false, prop: 'productName', label: '产品', sortable: false, visible: true,minwidth:140},
          {fixed: false, prop: 'accountName', label: '账号名称', sortable: false, visible: true,minwidth:250},
      ],
      table_column_: [
          {fixed: false, prop: 'todayBalance', label: '今日折后消耗', sortable: false, visible: true,minwidth:110},
          {fixed: false, prop: 'platformName', label: '平台', sortable: false, visible: true,minwidth:100},
          {fixed: false, prop: 'operator', label: '运营人', sortable: false, visible: true,minwidth:100},
      ],
      importCities: ['日期', '产品', '账号名称', '今日消耗', '今日折后消耗', '平台', '运营人'],
      citiesFilterVal: ['dataTime', 'productName', 'accountName', 'todayConsume', 'todayBalance', 'platformName', 'operator'],
      page: {
          sizes: [30, 50,100],
          offset: 1,
          limit: 10,
          count: 0,
          currentPage: 1,
      },
      platform_items: {
          model_value: '',
          placeHolder: '平台',
          options: [
          ]
      },
      account_items: {
          model_value: '',
          placeHolder: '账号',
          options: []
      },
      pro_items: {
          model_value: '',
          placeHolder: '产品',
          options: []
      },
      importPlatform:'',
      params: {
          date:''
      },
      source:null,
    }
  },
  computed:{
    paddingWidth(){
      return this.$store.state.paddingWidth;
    }
  },
  created(){
    this.$nextTick(function(){
    })
    this.platform();
    // this.pageInfo();
  },
  methods:{
      cancelQuest(){
        if(typeof this.source ==='function'){
            this.source('终止请求'); //取消请求
        }
      },
      /*页码翻页*/
      handleCurrentChange(val) {
        this.page.offset = val;
        this.pageInfo();
      },
      /*改变每页条数*/
      handleSizeChange(val) {
        this.page.limit = val;
        this.pageInfo();
      },
      /*select检索*/
      selectOne() {
          this.proInfo();
          this.pageInfo();
      },
      selectTwo() {
          this.account();
          this.pageInfo();
      },
      selectThree() {
          this.pageInfo();
      },
      /*平台*/
      platform(){
          this.$http({
              method: 'get',
              url: this.apiUrl.fdpPlaGetPlatformList,
          }).then(res => {
              console.log(res);
              if (res.status == 200) {
                  var data = res.data;
                  this.platform_items.options = data;
              } else {
              }
          }).catch(error => {
              console.log(error);
          });
      },
      /*账号*/
      account() {
          this.$http({
              method: 'get',
              url: this.apiUrl.fdpAccSearchAccount,
              params: {
                  offset: 1,
                  limit: 9999,
                  platformId: this.platform_items.model_value
              }
          }).then(res => {
              console.log(res);
              if (res.status == 200) {
                  var data = res.data;
                  this.account_items.model_value='';
                  this.account_items.options = data.items;
              } else {
              }
          }).catch(error => {
              console.log(error);
          });
      },
      /*产品*/
      proInfo() {
          this.pro_items.model_value=''
          this.$http({
              method: 'get',
              url: this.apiUrl.fdpProListall,
              params: {
                  platformId: this.platform_items.model_value||-1,
              }
          }).then(res => {
              console.log(res);
              if (res.status == 200) {
                  var data = res.data;
                  this.pro_items.options = data;
              } else {
              }
          }).catch(error => {
              console.log(error);
          });
      },
      /*查询表格数据*/
      pageInfo() {
          this.tableData=[];
          this.loading=true;
          const _this = this;
          this.cancelQuest(); //在请求发出前取消上一次未完成的请求
          this.$http({
              method: 'get',
              url: this.apiUrl.fdpAccSearch,
              params: {
                  curPage: this.page.offset,
                  limit: this.page.limit,
                  productId: this.pro_items.model_value||-1,
                  accountId: this.account_items.model_value||-1,
                  platformId: this.platform_items.model_value||-1,
                  sDateTime: this.params.date,
              },
              cancelToken: new axios.CancelToken(function executor(c) {_this.source = c;})
          }).then(res => {
              this.loading=false;
              console.log(res);
              if (res.status = 200) {
                  this.page.count = res.data.totalNums;
                  this.tableData = res.data.list;
                  if(this.tableData.length>0){
                      this.tableData.unshift({dataTime:'总计',todayConsume:res.data.todayAllConsume,todayBalance:res.data.dstCountAllConsume});
                  }
              }
          }).catch(function(thrown){
                if (axios.isCancel(thrown)) {
                    console.log('Request canceled', thrown.message);
                    console.log(_this.loading)
                } else {
                    _this.loading=false;
                }
          });
      },
      /*改变时间选择器*/
      dateChange() {
          console.log(this.dateValue)
          if (this.dateValue != '' && typeof this.dateValue != 'undefined' && this.dateValue!= null && this.dateValue!= null) {
              this.params.date = this.formatDateTime(this.dateValue[0], 'y/m/d')+'-'+this.formatDateTime(this.dateValue[1], 'y/m/d');
              this.pageInfo()
          } else {
              this.params.date = '';
          }
      },
      /*上传成功*/
      handleSuccess(response, file, fileList) {
          this.importTitleTxt = response.msg;
          this.importTitleStatus = true;
      },
      // 上传错误
      uploadError(err, file, fileList) {
          this.$message({
              type: 'error',
              message: '上传失败，请重试'
          });
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload(file) {
          if(this.importPlatform!=''){
              this.uploadData.platformId=this.importPlatform;
          }
          var fileName = file.name.split('.');
          var fileNameLen = fileName.length - 1;
          const extension = fileName[fileNameLen] === 'xlsx';
          const extension2 = fileName[fileNameLen] === 'xls';
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!extension && !extension2) {
              this.$message({
                  type: 'info',
                  message: '上传渠道包只能是 xlsx/xls 格式'
              });
          }
          if (!isLt2M) {
              this.$message({
                  type: 'info',
                  message: '上传包大小不能超过 2MB'
              });
          }
          return extension || extension2 && isLt2M;
      },
      /*导出*/
      importData() {
         if (this.tableData.length == 0) {
             this.$message({
                 type: 'info',
                 message: '请查询数据'
             });
             return false;
         }
         let tHeader = this.importCities;
         let filterVal = this.citiesFilterVal;
         let importData = this.tableData;
         let fileName = [this.params.date, this.platform_items.model_value,this.account_items.model_value, this.pro_items.model_value,  '账号数据'].join('_');
         this.handleDownload(tHeader, filterVal, importData, fileName);
      },
  }
}
</script>
<style>
.accountData .infoTable{
  width: 100%;
}
.upload-demo{
  display: inline-block;
  padding-right: 20px;
}
.accountData .Inp .el-input__inner{
    height: 24px;
}
</style>

